package com.xiaoshu.aop;

import com.xiaoshu.util.ValidationParamsUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能说明： 对Controller类方法进行统一的拦截操作，判断参数是否合法；
 *
 * @ com.ubtechinc.aop
 * <p>
 * Original @Author: deane.jia-贾亮亮,@2020/4/1@14:14
 * <p>
 * Copyright (C)2012-@2020 小树盛凯科技 All rights reserved.
 */
@Component
@Aspect
@Slf4j
public class ControllerParamValidationAspect {

    @Pointcut("execution(public * com.xiaoshu.controller..*.*(..))")
    private void anyMethod() {
        //Define the PointCut
    }

    @Around("anyMethod()")
    public Object doExecute(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        Object[] args = joinPoint.getArgs();
        log.info("<======Validation the Params : URL ======> :{}", request.getRequestURI());
        ValidationParamsUtils.validateParams(args);
        // when the params pass Validation, then continue;
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object object = joinPoint.proceed();
        stopWatch.stop();
        log.info("<====== Cost Time is： ======> :{} ms", stopWatch.getTotalTimeMillis());
        return object;
    }
}
